package com.example.singing.view;

import com.example.singing.MainApp;
import com.example.singing.manager.UserManager;
import com.example.singing.model.User;
import com.example.singing.util.AlertUtil;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.util.Duration;

/**
 * 登录界面
 */
public class LoginView extends VBox {
    private MainApp mainApp;
    private UserManager userManager;
    private VBox view;
    private StackPane viewContainer;
    private VBox loginBox;
    private VBox registerBox;
    private TextField usernameField;
    private PasswordField passwordField;
    private Button loginButton;
    private Button registerButton;
    private TextField regUsernameField;
    private PasswordField regPasswordField;
    private PasswordField regConfirmPasswordField;
    private TextField regFullNameField;
    private ComboBox<String> regRoleField;
    private Button regSubmitButton;
    private Button regBackButton;

    public LoginView(MainApp mainApp, UserManager userManager) {
        this.mainApp = mainApp;
        this.userManager = userManager;
        initComponents();
        createLoginBox();
        createRegisterBox();
        setupView();
    }

    /**
     * 初始化组件
     */
    private void initComponents() {
        usernameField = new TextField();
        passwordField = new PasswordField();
        loginButton = new Button("登录");
        registerButton = new Button("注册");
        regUsernameField = new TextField();
        regPasswordField = new PasswordField();
        regConfirmPasswordField = new PasswordField();
        regFullNameField = new TextField();
        regRoleField = new ComboBox<>();
        regSubmitButton = new Button("注册");
        regBackButton = new Button("返回登录");
    }

    /**
     * 创建登录界面
     */
    private void createLoginBox() {
        loginBox = new VBox(20);
        loginBox.setAlignment(Pos.CENTER);
        loginBox.setPadding(new Insets(40));

        // 使用纯色背景，确保兼容性
        BackgroundFill backgroundFill = new BackgroundFill(
                Color.web("#667eea"),
                CornerRadii.EMPTY,
                Insets.EMPTY
        );
        loginBox.setBackground(new Background(backgroundFill));

        // 标题
        Label titleLabel = new Label("歌唱比赛评分系统");
        titleLabel.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 32));
        titleLabel.setStyle("-fx-text-fill: white; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.3), 10, 0, 0, 3);");

        // 图标
        ImageView logoView = createLogo();
        logoView.setFitWidth(100);
        logoView.setFitHeight(100);
        logoView.setStyle("-fx-effect: dropshadow(gaussian, rgba(0,0,0,0.3), 10, 0, 0, 3);");

        // 表单容器 - 半透明磨砂玻璃效果
        VBox formContainer = new VBox(15);
        formContainer.setAlignment(Pos.CENTER);
        formContainer.setPadding(new Insets(30));
        formContainer.setStyle("-fx-background-color: rgba(255, 255, 255, 0.95); " +
                "-fx-background-radius: 15px; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.2), 15, 0, 0, 5);");

        // 用户名输入 - 添加焦点效果
        usernameField.setPromptText("用户名");
        usernameField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");
        usernameField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                usernameField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                        "-fx-border-radius: 25px; -fx-border-color: #667eea; -fx-border-width: 2px; -fx-font-size: 14px; " +
                        "-fx-padding: 0 15px; -fx-background-color: white;");
            } else {
                usernameField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                        "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                        "-fx-padding: 0 15px; -fx-background-color: white;");
            }
        });

        // 密码输入 - 添加焦点效果
        passwordField.setPromptText("密码");
        passwordField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");
        passwordField.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                passwordField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                        "-fx-border-radius: 25px; -fx-border-color: #667eea; -fx-border-width: 2px; -fx-font-size: 14px; " +
                        "-fx-padding: 0 15px; -fx-background-color: white;");
            } else {
                passwordField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                        "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                        "-fx-padding: 0 15px; -fx-background-color: white;");
            }
        });

        // 按钮容器
        HBox buttonContainer = new HBox(15);
        buttonContainer.setAlignment(Pos.CENTER);

        // 登录按钮 - 添加悬停和点击效果
        loginButton.setStyle("-fx-background-color: #667eea; -fx-text-fill: white; -fx-font-weight: bold; " +
                "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        loginButton.setOnMouseEntered(e -> {
            loginButton.setStyle("-fx-background-color: #5a67d8; -fx-text-fill: white; -fx-font-weight: bold; " +
                    "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        });
        loginButton.setOnMouseExited(e -> {
            loginButton.setStyle("-fx-background-color: #667eea; -fx-text-fill: white; -fx-font-weight: bold; " +
                    "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        });
        loginButton.setOnAction(e -> {
            // 添加点击动画效果
            loginButton.setScaleX(0.95);
            loginButton.setScaleY(0.95);
            Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
                loginButton.setScaleX(1.0);
                loginButton.setScaleY(1.0);
                handleLogin();
            }));
            timeline.play();
        });

        // 注册按钮 - 添加悬停和点击效果
        registerButton.setStyle("-fx-background-color: #764ba2; -fx-text-fill: white; -fx-font-weight: bold; " +
                "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        registerButton.setOnMouseEntered(e -> {
            registerButton.setStyle("-fx-background-color: #6b46c1; -fx-text-fill: white; -fx-font-weight: bold; " +
                    "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        });
        registerButton.setOnMouseExited(e -> {
            registerButton.setStyle("-fx-background-color: #764ba2; -fx-text-fill: white; -fx-font-weight: bold; " +
                    "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        });
        registerButton.setOnAction(e -> switchToRegister());

        buttonContainer.getChildren().addAll(loginButton, registerButton);

        // 组装表单
        formContainer.getChildren().addAll(usernameField, passwordField, buttonContainer);

        // 组装登录界面
        loginBox.getChildren().addAll(logoView, titleLabel, formContainer);
        // 添加进入动画
        loginBox.setOpacity(0);
        loginBox.setTranslateY(20);
        Timeline fadeIn = new Timeline(new KeyFrame(Duration.millis(500), event -> {
            loginBox.setOpacity(1);
            loginBox.setTranslateY(0);
        }));
        fadeIn.play();
    }

    /**
     * 创建注册界面
     */
    private void createRegisterBox() {
        registerBox = new VBox(20);
        registerBox.setAlignment(Pos.CENTER);
        registerBox.setPadding(new Insets(40));

        // 使用纯色背景，确保兼容性
        BackgroundFill backgroundFill = new BackgroundFill(
                Color.web("#667eea"),
                CornerRadii.EMPTY,
                Insets.EMPTY
        );
        registerBox.setBackground(new Background(backgroundFill));

        // 标题
        Label titleLabel = new Label("用户注册");
        titleLabel.setFont(Font.font("Microsoft YaHei", FontWeight.BOLD, 32));
        titleLabel.setStyle("-fx-text-fill: white; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.3), 10, 0, 0, 3);");

        // 表单容器 - 半透明磨砂玻璃效果
        VBox formContainer = new VBox(20);
        formContainer.setAlignment(Pos.CENTER);
        formContainer.setPadding(new Insets(30));
        formContainer.setStyle("-fx-background-color: rgba(255, 255, 255, 0.95); " +
                "-fx-background-radius: 15px; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.2), 15, 0, 0, 5);");

        // 创建表单Grid
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);
        grid.setAlignment(Pos.CENTER);
        grid.setPadding(new Insets(10));

        // 设置Grid中的标签样式
        Label usernameLabel = new Label("用户名:");
        usernameLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #555;");
        Label passwordLabel = new Label("密码:");
        passwordLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #555;");
        Label confirmLabel = new Label("确认密码:");
        confirmLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #555;");
        Label fullNameLabel = new Label("姓名:");
        fullNameLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #555;");
        Label roleLabel = new Label("角色:");
        roleLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #555;");

        // 设置组件样式 - 带焦点效果
        regUsernameField.setPromptText("请输入用户名");
        regUsernameField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");
        addFocusEffect(regUsernameField);

        regPasswordField.setPromptText("请输入密码");
        regPasswordField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");
        addFocusEffect(regPasswordField);

        regConfirmPasswordField.setPromptText("请再次输入密码");
        regConfirmPasswordField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");
        addFocusEffect(regConfirmPasswordField);

        regFullNameField.setPromptText("请输入真实姓名");
        regFullNameField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");
        addFocusEffect(regFullNameField);

        regRoleField.getItems().addAll("评委", "管理员");
        regRoleField.setValue("评委");
        regRoleField.setStyle("-fx-pref-width: 280px; -fx-pref-height: 45px; -fx-background-radius: 25px; " +
                "-fx-border-radius: 25px; -fx-border-color: #ddd; -fx-border-width: 1px; -fx-font-size: 14px; " +
                "-fx-padding: 0 15px; -fx-background-color: white;");

        // 添加组件到Grid
        grid.add(usernameLabel, 0, 0);
        grid.add(regUsernameField, 1, 0);
        grid.add(passwordLabel, 0, 1);
        grid.add(regPasswordField, 1, 1);
        grid.add(confirmLabel, 0, 2);
        grid.add(regConfirmPasswordField, 1, 2);
        grid.add(fullNameLabel, 0, 3);
        grid.add(regFullNameField, 1, 3);
        grid.add(roleLabel, 0, 4);
        grid.add(regRoleField, 1, 4);

        // 按钮容器
        HBox buttonContainer = new HBox(15);
        buttonContainer.setAlignment(Pos.CENTER);

        // 注册按钮 - 添加悬停和点击效果
        regSubmitButton.setStyle("-fx-background-color: #667eea; -fx-text-fill: white; -fx-font-weight: bold; " +
                "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        addButtonHoverEffect(regSubmitButton, "#667eea", "#5a67d8");
        regSubmitButton.setOnAction(e -> {
            // 添加点击动画效果
            regSubmitButton.setScaleX(0.95);
            regSubmitButton.setScaleY(0.95);
            Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
                regSubmitButton.setScaleX(1.0);
                regSubmitButton.setScaleY(1.0);
                handleRegister();
            }));
            timeline.play();
        });

        // 返回按钮 - 添加悬停和点击效果
        regBackButton.setStyle("-fx-background-color: #764ba2; -fx-text-fill: white; -fx-font-weight: bold; " +
                "-fx-pref-width: 120px; -fx-pref-height: 40px; -fx-background-radius: 20px; -fx-cursor: hand;");
        addButtonHoverEffect(regBackButton, "#764ba2", "#6b46c1");
        regBackButton.setOnAction(e -> switchToLogin());

        buttonContainer.getChildren().addAll(regSubmitButton, regBackButton);

        // 组装表单
        formContainer.getChildren().addAll(grid, buttonContainer);

        // 组装注册界面
        registerBox.getChildren().addAll(titleLabel, formContainer);
        // 添加进入动画
        registerBox.setOpacity(0);
        registerBox.setTranslateY(20);
        Timeline fadeIn = new Timeline(new KeyFrame(Duration.millis(500), event -> {
            registerBox.setOpacity(1);
            registerBox.setTranslateY(0);
        }));
        fadeIn.play();
    }

    /**
     * 设置主视图
     */
    private void setupView() {
        viewContainer = new StackPane();
        viewContainer.getChildren().add(loginBox);
        view = new VBox();
        view.getChildren().add(viewContainer);
        VBox.setVgrow(viewContainer, Priority.ALWAYS);
        HBox.setHgrow(viewContainer, Priority.ALWAYS);
    }

    /**
     * 创建logo图标
     */
    private ImageView createLogo() {
        try {
            // 创建一个简单的圆形作为logo
            Circle circle = new Circle(50);
            circle.setFill(Color.WHITE);
            circle.setStroke(Color.web("#667eea"));
            circle.setStrokeWidth(3);

            // 创建一个简单的音乐符号
            StackPane logoPane = new StackPane();
            logoPane.setPrefSize(100, 100);
            logoPane.getChildren().add(circle);

            // 创建一个简单的图像
            ImageView imageView = new ImageView();
            imageView.setFitWidth(100);
            imageView.setFitHeight(100);

            // 由于直接创建图像比较复杂，我们使用一个简单的占位符
            // 在实际应用中，您可以加载一个真实的图像文件
            Image placeholder = new Image(getClass().getResourceAsStream("/images/logo.png"));
            if (placeholder != null) {
                imageView.setImage(placeholder);
            }

            return imageView;
        } catch (Exception e) {
            // 如果创建失败，返回一个空的ImageView
            return new ImageView();
        }
    }

    /**
     * 为输入框添加焦点效果
     */
    private void addFocusEffect(TextField field) {
        String originalStyle = field.getStyle();
        field.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                field.setStyle(originalStyle.replace("-fx-border-color: #ddd;", "-fx-border-color: #667eea;").replace("-fx-border-width: 1px;", "-fx-border-width: 2px;"));
            } else {
                field.setStyle(originalStyle);
            }
        });
    }

    /**
     * 为密码框添加焦点效果
     */
    private void addFocusEffect(PasswordField field) {
        String originalStyle = field.getStyle();
        field.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                field.setStyle(originalStyle.replace("-fx-border-color: #ddd;", "-fx-border-color: #667eea;").replace("-fx-border-width: 1px;", "-fx-border-width: 2px;"));
            } else {
                field.setStyle(originalStyle);
            }
        });
    }

    /**
     * 为按钮添加悬停效果
     */
    private void addButtonHoverEffect(Button button, String originalColor, String hoverColor) {
        String originalStyle = button.getStyle();

        button.setOnMouseEntered(e -> {
            button.setStyle(originalStyle.replace("-fx-background-color: " + originalColor + ";", "-fx-background-color: " + hoverColor + ";"));
        });

        button.setOnMouseExited(e -> {
            button.setStyle(originalStyle);
        });
    }

    /**
     * 处理登录逻辑
     */
    private void handleLogin() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        // 验证输入
        if (username.isEmpty() || password.isEmpty()) {
            AlertUtil.showErrorAlert("登录失败", "用户名和密码不能为空");
            return;
        }

        // 验证用户
        User user = userManager.validateLogin(username, password);
        if (user != null) {
            // 登录成功，跳转到主界面
            mainApp.showMainView(user);
        } else {
            AlertUtil.showErrorAlert("登录失败", "用户名或密码不正确");
        }
    }

    /**
     * 处理注册逻辑
     */
    private void handleRegister() {
        String username = regUsernameField.getText();
        String password = regPasswordField.getText();
        String confirmPassword = regConfirmPasswordField.getText();
        String fullName = regFullNameField.getText();
        String role = regRoleField.getValue();

        // 验证输入
        if (username.isEmpty() || password.isEmpty() || fullName.isEmpty()) {
            AlertUtil.showErrorAlert("注册失败", "请填写所有必填字段");
            return;
        }

        if (!password.equals(confirmPassword)) {
            AlertUtil.showErrorAlert("注册失败", "两次输入的密码不一致");
            return;
        }

        // 检查用户名是否已存在
        if (userManager.getUserByUsername(username) != null) {
            AlertUtil.showErrorAlert("注册失败", "用户名已存在");
            return;
        }

        // 添加用户
        User newUser = new User(username, fullName, password, role);
        if (userManager.addUser(newUser)) {
            AlertUtil.showInfoAlert("注册成功", "用户注册成功，请登录");
            switchToLogin();
            clearRegisterFields();
        } else {
            AlertUtil.showErrorAlert("注册失败", "注册过程中出现错误");
        }
    }

    /**
     * 切换到注册界面
     */
    private void switchToRegister() {
        viewContainer.getChildren().clear();
        viewContainer.getChildren().add(registerBox);
    }

    /**
     * 切换到登录界面
     */
    private void switchToLogin() {
        viewContainer.getChildren().clear();
        viewContainer.getChildren().add(loginBox);
    }

    /**
     * 清空注册表单
     */
    private void clearRegisterFields() {
        regUsernameField.clear();
        regPasswordField.clear();
        regConfirmPasswordField.clear();
        regFullNameField.clear();
        regRoleField.setValue("评委");
    }

    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}